<template>
  <div class="permission-container">
    <div class="app-container">
      <!-- 表格 -->
      <el-card>
        <div style="text-align: right; margin-bottom: 20px">
          <el-button type="primary" size="small" @click="addPermission({type:1,pid:null})">添加权限</el-button>
        </div>
        <el-table border :data="list" row-key="id">
          <el-table-column label="名称" prop="name" />
          <el-table-column label="标识" prop="code" />
          <el-table-column label="描述" prop="description" />
          <el-table-column label="操作">
            <template #default="{row}">
              <el-button type="text" @click="addPermission({type:2,pid:row.id})">添加</el-button>
              <el-button type="text" @click="editPermission({id:row.id,code:row.code,name:row.name,type:row.type})">编辑</el-button>
              <el-button type="text" @click="delPermission(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <!-- 弹出层 -->
    <el-dialog :visible="showDialog" title="弹层标题" @close="closeDialog">
      <el-form ref="addForm" label-width="100px" :model="formData" :rules="rules">
        <el-form-item label="权限名称" prop="name">
          <el-input v-model="formData.name" />
        </el-form-item>
        <el-form-item label="权限标识" prop="code">
          <el-input v-model="formData.code" />
        </el-form-item>
        <el-form-item label="权限描述">
          <el-input v-model="formData.description" />
        </el-form-item>
        <el-form-item label="权限启用">
          <el-switch
            v-model="formData.enVisible"
            active-text="启用"
            active-value="1"
            inactive-text="不启用"
            inactive-value="0"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div style="text-align: right;">
          <el-button @click="closeDialog">取消</el-button>
          <el-button type="primary">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getPermissionList, updatePermission, addPermission, getPermissionDetail, delPermission } from '@/api/permission'
import transTree from '@/utils/transTree.js'
export default {
  name: 'Permission',
  data() {
    // 权限名不能与子节点现有的名称相同
    const validName = (rule, value, callback) => {
      let newArr = []
      // 判断是否是编辑状态，不
      if (this.formData.id) {
        newArr = this.nameList.filter(item => item.type !== this.formData.type && item.name !== this.catchName).map(item => item.name)
      } else {
        newArr = this.nameList.filter(item => item.type !== this.formData.type).map(item => item.name)
      }
      newArr.includes(value) ? callback(new Error('name已经存在不能重复')) : callback()
    }

    // 要求不能和同级出现重复 -> 要在生成的codeList基础上再做一层过滤 以type作为过滤条件
    const validateCode = (rule, value, callback) => {
      let newArr = []
      if (this.formData.id) {
        newArr = this.codeList.filter(item => item.type === this.formData.type && item.code !== this.catchCode).map(item => item.code)
      } else {
        newArr = this.nameList.filter(item => item.type === this.formData.type).map(item => item.code)
      }
      newArr.includes(value) ? callback(new Error('code已经存在不能重复')) : callback()
    }
    return {
      list: [],
      formData: {
        enVisible: '0', // 开启
        name: '', // 名称
        code: '', // 权限标识
        description: '', // 描述
        type: '', // 类型
        pid: '' // 添加到哪个节点下
      },
      showDialog: false,
      nameList: [],
      catchName: '',
      codeList: [],
      catchCode: '',
      rules: {
        name: [
          { validator: validName, trigger: 'blur' },
          { required: true, message: '权限名称为必填项', trigger: ['blur', 'change'] },
          { min: 1, max: 50, message: '权限名称长度为1-50字符', trigger: 'blur' }
        ],
        code: [
          { validator: validateCode, trigger: 'blur' },
          { required: true, message: '权限标识为必填项', trigger: ['blur', 'change'] },
          { min: 1, max: 50, message: '部门编码长度为1-50字符', trigger: 'blur' }

        ]
      }
    }
  },
  mounted() {
    this.hGetPermissionList()
  },
  methods: {
    // /获取列表
    async hGetPermissionList() {
      const res = await getPermissionList()
      this.list = transTree(res)

      this.codeList = res
      this.nameList = res
    },
    addPermission({ type, pid }) {
      this.formData.pid = pid
      this.formData.type = type
      this.openDialog()
    },
    openDialog() {
      this.showDialog = true
    },
    closeDialog() {
      this.showDialog = false
      this.resetForm()
    },
    // 清空表单
    resetForm() {
      this.$refs.addForm.resetFields()
      this.formData = {
        name: '',
        code: '',
        description: '',
        enVisible: '',
        type: null,
        pid: ''
      }
    },
    // 确认提交
    async confirm() {
      // 兜底校验
      this.$refs.addForm.validate(async valid => {
        if (this.formData.id) {
          await updatePermission(this.formData)
        } else {
          // 提交新增权限
          await addPermission(this.formData)
        }

        this.$message.success(`${this.formData.id ? '修改' : '新增'}成功`)
        // 更新列表
        this.hGetPermissionList()
        // 关闭弹窗
        this.closeDialog()
        // 清空表单
        this.resetForm()
      })
    },
    // 编辑
    async editPermission({ code, id, name }) {
      this.openDialog()
      const res = await getPermissionDetail(id)
      this.formData = res

      this.catchName = name
      this.catchCode = code
    },
    delPermission(id) {
      this.$confirm('你确定要删除该权限吗？', '提示').then(async() => {
        await delPermission(id)
        this.$message.success('删除成功')
        // 更新列表
        this.hGetPermissionList()
      }).catch(() => {
        console.log('取消')
      })
    }

  }
}
</script>
